import { type ReactNode } from 'react';
import RightLayoutAdmin from '@/app/[locale]/admin/common/right';
import LeftLayoutAdmin from '@/app/[locale]/admin/common/left';
import { authMiddleware } from '@/lib/api';
import { cookies } from 'next/headers';
import { clientQueryAllMenu, queryPath } from '@/services/api';
import type { IMenu, IPath } from '@/interfaces';

async function getData() {
  try {
    const token = authMiddleware(cookies());
    const req1 = queryPath({
      baseURL: process.env.APP_API_SERVER,
      token,
      query: {
        name: '/',
      },
    });
    const req2 = clientQueryAllMenu({
      baseURL: process.env.APP_API_SERVER,
      token,
    });

    const responses = await Promise.all([req1, req2]);
    const resp1 = await ((await responses[0]) as Response).json();
    const resp2 = await ((await responses[1]) as Response).json();

    return {
      isSuccess: true,
      path: resp1.data as IPath,
      menus: resp2.data as IMenu[],
    };
  } catch (e) {
    return {
      isSuccess: false,
    };
  }
}

export default async function DashboardLayout({
  children,
  params: { locale },
}: {
  children: ReactNode;
  params: { locale: string };
}) {
  const data = await getData();

  if (data.isSuccess) {
    return (
      <div className="col">
        <div className="row">
          <div className="col-12 col-xxl-3 col-xl-4 col-lg-5 col-md-6 py-3 yw-left-layout-admin">
            <LeftLayoutAdmin
              path={data.path!}
              menus={data.menus!}
              locale={locale}
            />
          </div>
          <div className="col py-3 overflow-hidden yw-right-layout-admin">
            <RightLayoutAdmin>{children}</RightLayoutAdmin>
          </div>
        </div>
      </div>
    );
  }

  return <>{children}</>;
}
